/*
 * @Author: wangkg wangkegui@longfor.com
 * @Date: 2024-08-06 10:35:54
 * @Description:
 */
import type { UserInfo } from '#/store';
import { defineStore } from 'pinia';
import { store } from '@/store';
import { TOKEN_KEY } from '@/enums/cache-enum';
import { getAuthCache, setAuthCache } from '@/utils/auth';
import { getUserInfo, doLogout } from '@/apis/sys/user';

interface UserState {
  userInfo: Nullable<UserInfo> | object;
  token?: string;
  homePath?: string;
}

export const useUserStore = defineStore({
  id: 'app-user',
  state: (): UserState => ({
    // user info
    userInfo: {},
    // token
    token: undefined
  }),
  getters: {
    getUserInfo(state): UserInfo | object {
      return state.userInfo || {};
    },
    getToken(state): string {
      return state.token || getAuthCache(TOKEN_KEY);
    }
  },
  actions: {
    setToken(info: string | undefined) {
      this.token = info ? info : ''; // for null or undefined value
      setAuthCache(TOKEN_KEY, info);
    },
    setUserInfo(info: any) {
      this.userInfo = info;
    },
    resetState() {
      this.userInfo = null;
      this.token = '';
    },
    async getUserInfoAction() {
      const { success, data } = await getUserInfo();
      if (success) {
        this.setUserInfo(data);
        return data;
      }
    },

    /**
     * @description: Confirm before logging out
     */
    async confirmLoginOut() {
      try {
        const data = await doLogout();
        if (data) {
          window.location.href = data;
          this.setUserInfo(null);
        }
      } catch {
        console.log('注销登陆失败');
      }
    }
  }
});

// Need to be used outside the setup
export function useUserStoreWithOut() {
  return useUserStore(store);
}
